<?php

class CustomerGlobalContactsController extends Controller {

    public function actionList($custno = NULL, $query = NULL, $page = 1, $sort = NULL, $dir = NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);
        $criteria = new CDbCriteria();
        if ($sort != NULL) {
            $criteria->order = $sort != NULL ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL;
        }
        if ($custno != NULL) {
            $criteria->compare('custno', $custno);
            $criteria->compare('locno', '00000');
        }
        $contacts = new CActiveDataProvider('Locationcontacts', array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    )
                ));
        $rs = array();
        if (count($contacts->getData()) > 0) {
            $rs['totalCount'] = $contacts->getTotalItemCount();
            $rs['type'] = 'Locationcontacts';
            foreach ($contacts->getData() as $item) {
                $rs['data'][] = $item->getAttributes();
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
    }

    public function actionUpdate($id,$custno) {
      if((int)$id)
         $model = $this->loadModel($id);
     else {
     $model = new Locationcontacts();    
     }
            $model->locno = '00000';
        $model->custno = $custno;

        if (isset($_POST)) {
            $model->attributes = $_POST;
            if ($model->save()){
                $this->showAjaxMessage('',true);
            }
        }else {
               $this->showAjaxMessage($model->getErrors(),false);
        }
        
      
    }

    public function actionDelete($id) {
        echo json_encode($this->loadModel($id)->delete());
    }

    public function actionCreate($custno) {
        $model = new Locationcontacts();
        $model->locno = '00000';
        $model->custno = $custno;
        $model->attributes = $_POST;
        if($model->save()){
            $this->showAjaxMessage('',true);
        }else{
            $this->showAjaxMessage($model->getErrors(),false);
        }
         
        
    }
      public function loadModel($id) {
        $model = Locationcontacts::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

}